"use strict";
//台湾工口平台
const crypto = require('crypto')
const request = require('request')
const axios = require('axios').default
// const querystring = require('querystring')
const mvc = require('cosjs.mvc')
const base64 = mvc.library('crypto/base64')
// const moment = require('moment')

//订单记录分隔符
const ORDERATTACHSPLIT = "|"

// const URI = 'https://public.exaggre.com/'
// const IP_LIST = [
//     '23.99.115.89',
//     '23.99.116.84',
//     '23.99.116.67',
//     '23.99.114.174',
// ]
// const VERSION = '1.0'


exports.format = {
    "id": 'tw',
    "name": "台湾工口平台",
    "fields": {
        "gameId": {'type': 'int', 'val': 0, 'name': "游戏id"},
        "md5": {'type': 'string', 'val': '', 'name': "Md5 key"},
        "apiUrl": {'type': 'string', 'val': '', 'name': "apiUrl"},
        // "tw" :{'type':'int','val':0,'name':"平台","option":{"0":"移动端","1":"PC端"}  },
        // "key" :{'type':'string','val':'','name':"consumerKey"},
        // "secret" :{'type':'string','val':'','name':"consumerSecret"},
        // "pageurl" :{'type':'string','val':'','name':"finishPageUrl[移动端]"},
        // "servurl" :{'type':'string','val':'','name':"DMM安全验证服务器地址(URL/social/rest/)"},
        "tapdbUrl":  {'type':'string','val':'','name':"tapdb推送url"},
        "tapdbApp":  {'type':'string','val':'','name':"tapdb appid"},
    }
}

//==========================================入口=================================================//
//登录与认证TOKEN
exports.login = async function () {

    let token = this.get("token", 'string');
    let userinfo = this.get("userinfo", 'json');

    if (!token || !userinfo) {
        return this.error("args empty");
    }

    return {
        "token": token,
        "openid": userinfo.account || userinfo.user_id
    }

}


//游客绑定
exports.bind = async function () {
    // let username = this.get("username");
    let guid = this.get("guid");
    let token = this.get("token", 'string');
    let userinfo = this.get("userinfo", 'json');

    if (!guid || !token || !userinfo || !userinfo.account) {
        return this.error("args empty");
    }

    let openidModel = this.model.branch("openid", this.branch);

    let openid = await openidModel.get(guid);

    if (!openid) {
        return this.error("account not exists", guid);
    }

    let ret = requestCommon.call(this, {}, 'checkBindGameStatus', 0, token)

    if(ret.is_bound) {
        return this.error("account bind already", guid, ret.bind);
    }

    await openidModel.set(openid._id, {
        "token": token,
        bind: userinfo.account,
        "nickname": userinfo.nickname,
        "openid": userinfo.account
    });

    return {
        guid: guid,
        token: token,
        userinfo: userinfo
    }

    // return this.success();
}

//查询平台比
exports.coins = async function () {

    return await requestCommon.call(this, {}, 'getUserCoins')

}

exports.orderCreate = async function (config) {

    // let attach = config['attach'];
    let orderid = config['orderid'];
    if(!config['attach']){
        return this.error("order_attach_error",config['attach']);
    }
    let s = config['attach'].indexOf("|") >0 ? "|" :"z";
    let arr = config['attach'].split(s);
    let uid = arr[0],sid = parseInt(arr[1]),id = arr[2];
    if(!uid || !sid || !id){
        return this.error("order_attach_error",config['attach']);
    }

    let body = {
        exchange_coins: config.rmb,
        transaction_id: orderid,
    }

    await requestCommon.call(this, body, 'exchangeCoins', config.guid)

    let _body = {
        transaction_id: orderid,
    }

    await requestCommon.call(this, _body, 'checkExchangeCoins', config.guid)

    let query = {"id":id,"uid":uid,"cyt":this.opensdk['cyt'],"sdk":this.opensdk._id,"amount":config.rmb,"orderid":config['orderid'] };

    try {
        await this.library("game/notify",this.branch,sid,query);
    } catch (err) {
        if (err && err['err'] !== 'success') {
            console.log(JSON.stringify(err))
            return await Promise.reject(err)
        }
    }

    if(this.opensdk.setting.tapdbApp) {
        paymentPush.call(this, config, uid)
            .catch(err => {
                console.log('tapdb充值推送失败：', JSON.stringify(err))
            })

    }

    let data = {};
    data["attach"] = orderid;               //自己记录attach透传参数为orderid
    data["orderid"] = orderid;
    return data;

}

//通用request
async function requestCommon(p, path, _guid, _token) {

    let ret
    if(!_token) {
        let guid = _guid || this.get("guid");

        if (!guid) {
            return this.error("args empty");
        }

        let openidModel = this.model.branch("openid", this.branch);

        ret = await openidModel.get(guid);

        if (!ret || !ret.guid) {
            console.debug('guid error', ret)
            return this.error("guid error");
        }
    }


    let form = {
        game_id: this.opensdk.setting.gameId,
    }

    if(path === 'exchangeCoins') {
        form.request = base64.encode(JSON.stringify(p))
        form.signMsg = createSign.call(this, form.request)
    } else {
        Object.assign(form, p)
    }

    // console.log(form)
    // let token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZmJjMWFkMWMtYjdhNC00NDM2LTk4MGMtZDQxMjhjZmUzZTJkIiwidG9rZW5faWQiOiJjYzY2ZmIwZi05MmJlLTQzNzYtOWUyNC1jNWM3MDQwZDkyMGYiLCJpYXQiOjE2MDQ1NTgxOTN9.RXRvABSRYJ121cuGKRoc-DDpu30-vcC8OXE-APcjhcw00pEu6cYz7KSa5yMeV68TPhIx3FT70bz-NyD1aGGz8hQaY5oO3zJO1nTA23cD8W9yfd3etpTtCNh0HRojlCqCPDQFoN2BG9GKlOTdPGCPge8efTY0HxBjLROBtZbM5hFp2s4hDkD47cAWLDLraMyTjBy-waVqnqJq7XtqlUNpdo12Zg1YzjMTFAdaghqfxLrgnmTOOcNj1lITBQ8VvLW9vAA5PKgdlLE_TutgMzkgsNhHR6qE3m0AzkLYYXBJYQmcJHAXFJYaOphMYJLHOAB17sFDAvbt7mF7LqPqIYPWRg'

    let options = {
        method: 'POST',
        url: this.opensdk.setting.apiUrl + path,
        form: form,
        headers: {
            'Content-type': 'application/x-www-form-urlencoded',
            Accept: 'application/json',
            Authorization: _token || ret.token
        }
    }

    return await new Promise((resolve, reject) => {
        request(options, function (err, res, body) {
            if (err) {
                reject(err)
            } else {
                let json = JSON.tryParse(body) || body;
                if (json.result !== '0000') {
                    reject(json.reason)
                } else {
                    resolve(json);
                }
            }
        })
    })

}

//==========================================公共方法=================================================//
function createSign(request) {

    let str = createKeyValueString({
        game_id: this.opensdk.setting.gameId,
        request: request,
    })
    str += '&key:' + this.opensdk.setting.md5
    let md5 = mvc.library("crypto/md5", str);
    return md5.toUpperCase()
}


function createKeyValueString(params) {
    let kvStringList = []
    for (let key in params) {
        let value = params[key]
        let kvString = `${key}:${value}`
        kvStringList.push(kvString)
    }
    kvStringList.sort((a, b) => {
        return a.localeCompare(b)
    })
    return kvStringList.join("&")
}

//充值推送接口 tapdb
function paymentPush(data, uid) {
    let url
    if (this.opensdk.setting && this.opensdk.setting.tapdbUrl) {
        url = this.opensdk.setting.tapdbUrl
    }

    let ip = this.req.ip.replace("::ffff:",'');

    let json = {
        "module": "GameAnalysis", // 固定参数
        "ip": ip, // 可选。充值用户的IP
        "name": "charge", // 固定参数
        "index": this.opensdk.setting.tapdbApp, // 必需。注意APPID需要被替换成TapDB的appid
        "identify": uid, // 必需。用户ID。必须和SDK的setUser接口传递的userId一样，并且该用户已经通过SDK接口进行过推送
        "properties": {
            "order_id": data.orderid, // 可选。长度大于0并小于等于256。订单ID。传递订单ID可进行排重，防止计算多次
            "amount": data.rmb / 10 * 100, //这里的rmb是honeyP,对应人民币要除10  // 必需。大于0并小于等于100000000000。充值金额。单位分，即无论什么币种，都需要乘以100
            "currency_type": 'CNY', // 可选。货币类型。国际通行三字母表示法，为空时默认CNY。参考：人民币 CNY，美元 USD；欧元 EUR
            "product": data.id.toString(), // 可选。长度大于0并小于等于256。商品名称
            "payment": 'HoneyP' // 可选。长度大于0并小于等于256。充值渠道
        }
    }

    let body = JSON.stringify(json)
    body = encodeURIComponent(body)
    return axios.post(url, body)

}